#include <iostream>
#include <vector>
#include <string>
#include <string.h>
#include <unistd.h>
using namespace std;

int Test1(){
  pid_t id = fork();
  if(id < 0)
  {
    //创建失败
    cerr << "fork" << endl;
    return 1;
  }
  else if(id == 0)
  {
    //子进程执行流
      cout << "I'm child process, ";
      cout << "pid:" << getpid() << " ";
      cout << "ppid:" << getppid() << endl;
      sleep(3);
    return 0;
  }
  else{
    //父进程执行流
    while(1)
    {
      cout << "I'm parent process, ";
      cout << "pid:" << getpid() << " ";
      cout << "ppid:" << getppid() << endl;
      sleep(1);
    }
    return 0;
  }
}

int Test2(){
  pid_t id = fork();
  if(id < 0)
  {
    //创建失败
    cerr << "fork" << endl;
    return 1;
  }
  else if(id == 0)
  {
    //子进程执行流
    while(1)
    {
      cout << "I'm child process, ";
      cout << "pid:" << getpid() << " ";
      cout << "ppid:" << getppid() << endl;
      sleep(1);
    }
    return 0;
  }
  else{
    //父进程执行流
      cout << "I'm parent process, ";
      cout << "pid:" << getpid() << " ";
      cout << "ppid:" << getppid() << endl;
      sleep(3);
    return 0;
  }
}

//进程优先级
int Test3(){
  while(1)
  {
    cout << "hello world!" <<endl;
    sleep(1);
  }
}

void Test4(){
  char * env = getenv("MYENV");
  if(env != NULL)
  {
    cout << "MYENV: " << env <<endl;
  }
  else{
    cout << "variable do not exist!" << endl;
  }
}


//int main(){
//  //return Test1();
//  //Test2();
//  Test3();
//  return 0;
//}

//环境变量
//int main(int argc, char* argv[], char* env[]){
//int main(){
//  //int i = 0;
//  //while(environ[i] != NULL)
//  //{
//  //  cout << environ[i] << endl;
//  //  ++i;
//  //}
//  //for(int i = 0; i < argc; ++i)
//  //{
//  //  cout << argv[i] << endl;
//  //}
//  Test4();
//  return 0;
//}

int main(int argc, char** argv){

  if(argc == 1)
  {
    cout << "Run without option!" << endl;
    return 0;
  }

  //程序中内置的选项
  vector<string> options;
  options.push_back("-a");
  options.push_back("-b");
  options.push_back("-c");
  options.push_back("-d");

  //匹配查找输入的选项
  int i = 1;
  while(i < argc)
  {
    bool ret = false;
    for(string& e : options)
    {
      if(strcmp(argv[i], e.c_str()) == 0){
        ret = true;
        cout << "option: " << e << endl;
      }
    }
    if(!ret)
    {
      cout << "option " << argv[i] << " is not available!" << endl; 
      return 1;
    }
    ++i;
  }

  return 0;
}
